import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_01/example/webPage.dart';
import 'model/news.dart';
import 'dart:convert';

class NewsPage extends StatefulWidget {
  NewsPage({Key key, this.title}) : super(key: key);
  final String title;

  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State {
  var dataList = <News>[];
  var _currentIndex = 0;

  @override
  void initState() {

    _loadData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Flutter News'),
        backgroundColor: Color.fromARGB(255, 207, 64, 65),
        // bottom: TabBar(
        //   tabs: <Widget>[
        //     Tab(icon: Icon(Icons.directions_bike)),
        //     Tab(icon: Icon(Icons.directions_car)),
        //   ],
        // ),
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: _creatListView(),
      ),
    );
  }

  Future<Null> _refresh() async {
    await _loadData();
    return;
  }

  void _loadData() async {
    // http://m.toutiao.com/list/?tag=__all__&ac=wap&count=15&format=json_raw&as=A17538D54D106FF&cp=585DF0A65F0F1E1&min_behot_time=1482491618&offset=0
    var httpClient = new HttpClient();
    var uri = new Uri.http('m.toutiao.com', 'list', {
      'tag': '__all__',
      'ac': 'wap',
      'count': '20',
      'format': 'json_raw',
      'as': 'A17538D54D106FF',
      'cp': '585DF0A65F0F1E1',
      'min_behot_time': '1482491618',
      'offset': '0'
    });
    var request = await httpClient.getUrl(uri);
    var resp = await request.close();
    var respBody = await resp.transform(utf8.decoder).join();
    Map<String, dynamic> map = jsonDecode(respBody);
    var list = map['data'];
    dataList.clear();
    setState(() {
      for (Map<String, dynamic> item in list) {
        dataList.add(News.fromJson(item));
      }
    });
  }

  Widget _creatListView() {
    return new ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, i) {
        return _creatListCell(dataList[i]);
      },
    );
  }

  Widget _creatListCell(News item) {
    return new GestureDetector(
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new WebPage(
            url: item.url,
            title: item.title,
          );
        }));
      },
      child: new Container(
        padding: const EdgeInsets.only(left: 16.0, right: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Container(
                padding: const EdgeInsets.only(bottom: 8, top: 12),
                child: new Text(
                  item.abstract ?? (item.title ?? ''),
                  style: TextStyle(fontSize: 14.0),
                )),
            new Container(
              padding: const EdgeInsets.only(bottom: 8),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new Expanded(
                    flex: 1,
                    child: new ClipRRect(
                      borderRadius: BorderRadius.circular(3.0),
                      child: item.image_list.length > 0 ?  new Image.network(
                        item.image_list[0]['url'],
                        height: 80,
                        fit: BoxFit.cover,
                      ) : new Container(),
                    ),
                  ),
                  new Container(
                    width: 8,
                  ),
                  new Expanded(
                    flex: 1,
                    child: new ClipRRect(
                      borderRadius: BorderRadius.circular(3.0),
                      child: item.image_list.length > 1 ? new Image.network(item.image_list[1]['url'],
                          height: 80, 
                          fit: BoxFit.cover) : new Container(),
                    ),
                  ),
                  new Container(
                    width: 8,
                  ),
                  new Expanded(
                    flex: 1,
                    child: new ClipRRect(
                      borderRadius: BorderRadius.circular(3.0),
                      child: item.image_list.length > 2 ? new Image.network(item.image_list[2]['url'],
                          height: 80, 
                          fit: BoxFit.cover) : new Container(),
                    ),
                  )
                ],
              ),
            ),
            _bottomSectionWidget(item),
            new Divider(
              height: 0.5,
              color: Colors.grey[300],
            )
          ],
        ),
      ),
    );
  }

  // Widget
  Widget _bottomSectionWidget(News item) => new Container(
    padding: const EdgeInsets.only(bottom: 8),
    child: new Row(
      children: <Widget>[
        new Container(
          margin: const EdgeInsets.only(right: 4),
          child: new Text(item.media_name ?? '',
              style: TextStyle(fontSize: 12.0, color: Colors.grey[400])),
        ),
        new Container(
            margin: const EdgeInsets.only(right: 4),
            child: new Text("${item.comment_count}评论",
                style: TextStyle(fontSize: 12.0, color: Colors.grey[400]))),
        new Container(
            margin: const EdgeInsets.only(right: 4),
            child: new Text(item.datetime,
                style: TextStyle(fontSize: 12.0, color: Colors.grey[400]))),
      ],
    ),
  );
}